import type { RouteRecordRaw } from 'vue-router'

import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useNProgress } from '@fl/hooks/web/useNProgress'
import { usePageLoading } from '@fl/hooks/web/usePageLoading'
import { useTitle } from '@fl/hooks/web/useTitle'
// import { useAppStoreWithOut } from '@fl/store/modules/app'
import { useUserStoreWithOut } from '@fl/store/modules/user'

import router from './router'

const { done, start } = useNProgress()

const { loadDone, loadStart } = usePageLoading()

router.beforeEach(async (to, from, next) => {
    start()
    loadStart()
    const permissionStore = usePermissionStoreWithOut()
    // const appStore = useAppStoreWithOut()
    const userStore = useUserStoreWithOut()
    if (userStore.getUserInfo) {
        if (to.path === '/login') {
            next({ path: '/' })
        }
        else {
            if (permissionStore.getIsAddRouters) {
                next()
                return
            }

            // 开发者可根据实际情况进行修改
            const roleRouters = userStore.getRoleRouters || []

            // 处理顶部菜单栏
            const menuList = toRaw(roleRouters).reduce((pre: any, cur: any) => {
                const obj = { label: '', path: '' }
                obj.label = cur?.meta.title
                obj.path = cur.path
                pre.push(obj)
                return pre
            }, [])
            // console.log('menuList', menuList)
            window.sessionStorage.setItem('TOP_MENU', JSON.stringify(menuList))
            // 首次进入重定向
            window.sessionStorage.setItem('FIRST_REDIRECT', menuList[0]?.path || '/login')

            // 1.（新）
            await permissionStore.generateRoutes('server', roleRouters as AppCustomRouteRecordRaw[])
            // await permissionStore.generateRoutes('static')

            // 2.（原）
            // 是否使用动态路由
            // if (appStore.getDynamicRouter) {
            //     appStore.serverDynamicRouter
            //         ? await permissionStore.generateRoutes('server', roleRouters as AppCustomRouteRecordRaw[])
            //         : await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
            // }
            // else {
            //     await permissionStore.generateRoutes('static')
            // }

            permissionStore.getAddRouters.forEach((route) => {
                router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
            })

            // （原）
            // const redirectPath = from.query.redirect || to.path
            // const redirect = decodeURIComponent(redirectPath as string)

            // （新）
            const redirectPath = computed(() => {
                if (from.query.redirect && from.query.redirect !== '/null') {
                    return from.query.redirect
                }
                else if (to.path && to.path !== '/null' && to.path !== '/404') {
                    return to.path
                }
                else if (permissionStore.getAddRouters[0]?.path !== '/:path(.*)*') {
                    return permissionStore.getAddRouters[0].path
                }
                else {
                    return '/404'
                }
            })
            const redirect = decodeURIComponent(redirectPath.value as string)
            // console.log('redirect', redirect)

            // 初始进入路由时候的精准分片
            let nextData
            let pathPrefix
            if (to.path === redirect) {
                nextData = { ...to, replace: true }
                pathPrefix = to.fullPath.match(/^\/[^/]+/)?.[0]
            }
            else {
                nextData = { path: redirect }
                pathPrefix = redirect!.match(/^\/[^/]+/)?.[0]
            }
            // console.log('nextData', nextData)

            permissionStore.setSliceRouters(pathPrefix ?? '/')
            permissionStore.setIsAddRouters(true)

            // next(nextData)

            if (nextData.path === '/404') {
                userStore.setUserInfo(undefined)
                next(`/login`)
            }
            else {
                next(nextData)
            }
        }
    }
    else {
        if (['/login'].includes(to.path))
            next()
        else
            next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
})

router.afterEach((to) => {
    useTitle(to?.meta?.title as string)
    done() // 结束Progress
    loadDone()
})
